<?php

// +----------------------------------------------------------------------
// | liftforgames.com [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Author: tangyin <cicicoco321@163.com> QQ:545764358
// +----------------------------------------------------------------------


namespace app\admin\controller;

use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\Controller;
use think\facade\View;
use app\common\model\Fields as FieldsModel;
use app\common\model\Module as ModuleModel;
use app\common\model\Example as ExampleModel;
use app\common\model\ExampleGroup as ExampleGroupModel;
use app\common\model\SystemMenu as SystemMenuModel;

class Module extends Base
{
    function __construct(){
        parent::__construct();
        $field_pattern = [
            ['name'=>'defaul','title'=>'默认'],
            ['name'=>'email','title'=>'电子邮件'],
            ['name'=>'url','title'=>'网址'],
            ['name'=>'date','title'=>'日期'],
            ['name'=>'number','title'=>'有效的数值'],
            ['name'=>'digits','title'=>'数字'],
            ['name'=>'creditcard','title'=>'信用卡号码'],
            ['name'=>'equalTo','title'=>'再次输入相同的值'],
            ['name'=>'ip4','title'=>'IP'],
            ['name'=>'mobile','title'=>'手机号码'],
            ['name'=>'zipcode','title'=>'邮编'],
            ['name'=>'qq','title'=>'QQ'],
            ['name'=>'idcard','title'=>'身份证号'],
            ['name'=>'chinese','title'=>'中文字符'],
            ['name'=>'cn_username','title'=>'中文英文数字和下划线'],
            ['name'=>'tel','title'=>'电话号码'],
            ['name'=>'english','title'=>'英文'],
            ['name'=>'en_num','title'=>'英文数字和下划线'],
        ];
        View::assign('pattern',$field_pattern);
    }
    
    public function index()
    {
        if(IS_AJAX){
            $param = input("param.");
            $ModuleModel = new ModuleModel();
            $res = $ModuleModel ->tableData($param);
            return dyajaxReturn(1,'获取成功',$res['data'],'',$res['count']);
        }else{



            return View::fetch();
        }

    }
    //模型添加
    public function add(){
        if($_POST){
            $post = input('post.');

            $database = DATABASE;//数据库名
            $prefix = PREFIX;//表前缀

            if (!preg_match("/[A-Za-z0-9]+/", strtolower($post['name']))) {
                //return $this->error('请输入英文或数字的表名');
                return dyajaxReturn(0,"请输入英文或数字的表名");
            }

            //在module表中在模型是否存在
            $name_res = DB::name('module')->where('name',$post['name'])->find();
            if($name_res){
                $name = $post['name'].'表已存在';
                return dyajaxReturn(0,$name);
            }
            //在数据库中查表是否存在
            $sql = "select table_name from information_schema.tables where table_schema='".$database."' and table_name='".$prefix.$post['name']."'";
            $biao =  DB::query($sql);
            if($biao){
                $name = $post['name'].'表已存在于数据库中';
                return dyajaxReturn(0,$name);
            }

            $ModuleModel = new ModuleModel();
            $res = $ModuleModel->add($post);
            //return dyajaxReturn(1,"43543",$res);
            return dyajaxReturn($res['code'],$res['msg']);
        }else{
            //示例表
            $ExampleModel = new ExampleModel();
            $ex_res = $ExampleModel -> where("status","=",1)
                ->order("id asc")
                ->select();

            //节点列表
            $SystemMenuModel = new SystemMenuModel();
            $sys_list = $SystemMenuModel -> where('is_del','=',0)->order('id asc')->select();
            $tree = $SystemMenuModel->menulist($sys_list,0,0);

            View::assign('tree',$tree);
            View::assign('ex_res',$ex_res);
            return View::fetch();
        }
    }
    //添加组合
    public function add_group(){
        $param = input("param.");
        $ExampleGroupModel = new ExampleGroupModel();
        if(IS_POST){
            $example_group_id = $param['example_group_id'];
            $example_ids = $param['example_ids'][$example_group_id];
            $ExampleModel = new ExampleModel();
            foreach($example_ids as $k=>$v){
                $examp_one = $ExampleModel -> where("id","=",$v)->find();
                $name = $examp_one['name'];
                $database = DATABASE;//数据库名
                $prefix = PREFIX;//表前缀

                if (!preg_match("/[A-Za-z0-9]+/", strtolower($name))) {
                    return dyajaxReturn(0,"请输入英文或数字的表名");
                }

                //在module表中在模型是否存在
                $name_res = DB::name('module')->where('name',$name)->find();
                if($name_res){
                    $name = $name.'表已存在';
                    return dyajaxReturn(0,$name);
                }
                //在数据库中查表是否存在
                $sql = "select table_name from information_schema.tables where table_schema='".$database."' and table_name='".$prefix.$name."'";
                $biao =  DB::query($sql);
                if($biao){
                    $name = $name.'表已存在于数据库中';
                    return dyajaxReturn(0,$name);
                }
            }
            $ModuleModel = new ModuleModel();
            foreach($example_ids as $k=>$v){
                $examp_one = $ExampleModel -> where("id","=",$v)->find();

                $data['title'] = $examp_one['title'];
                $data['name'] = strtolower($examp_one['name']);
                $data['description'] = $examp_one['title'];
                $data['status'] = 1;
                $data['orderid'] = GetOrderID('module');
                $data['add_time'] = time();
                $data['emptytable'] = $v;
                $data['isdel'] = 1;
                $data['isadd'] = 1;
                $data['type'] = 1;

                $ModuleModel->add($data);
            }

            return dyajaxReturn(1,"添加成功");
        }else{
            $eg_res = $ExampleGroupModel -> where("status","=",1)->order("id asc")->select();
            $ExampleModel = new ExampleModel();
            foreach ($eg_res as $k=>$v){
                $e_res = $ExampleModel -> where("id","in",$v['example_ids'])->select();
                $eg_res[$k]['e_res'] = $e_res;
            }

            View::assign('eg_res',$eg_res);
            return View::fetch();
        }
    }


    public function edit(){
        $param = input("param.");
        if($_POST){
            $post = input('post.');
            $id = $post['id'];
            unset($post['id']);
            
            $res = DB::name('module')->where('id',$id)->update($post);
            if(!$res){
                return dyajaxReturn(0,"修改失败");
            }
            $module_one = DB::name('module')->where('id',$id)->find();
            adminLog("模型修改",$id);
            return dyajaxReturn(1,"修改成功");
        }else{
            $id = $param['id'];
            $row = DB::name('module')->where('id',"=",$id)->find();
            View::assign('info',$row);
            return View::fetch();
        }
    }

    //删除模型
    public function delete(){
        $id =input('param.id');

        $ModuleModel = new ModuleModel();
        $FieldsModel = new FieldsModel();
        $r = $ModuleModel->find($id);
        if(!empty($r)){
            $tablename = PREFIX.$r['name'];
            Db::startTrans();
            try {
                $is_module_del = $ModuleModel->where("id","=",$id)->delete();
                if(!$is_module_del){
                    Db::rollback();
                    return dyajaxReturn(0,"模型表删除失败");
                }
                $is_fields_del = $FieldsModel -> where("moduleid","=",$id)->delete();
//                if(!$is_fields_del){
//                    Db::rollback();
//                    return dyajaxReturn(0,"字段表删除失败");
//                }
                //删除表
                Db::execute("DROP TABLE IF EXISTS `".$tablename."`");
                //删除节点
                DB::name("system_menu")->where("module_id","=",$r['id'])->delete();
                Db::commit();
                adminLog($r['title']."模型删除",$id);
                return dyajaxReturn(1,"模型删除成功");
            } catch (\Exception $e) {
                Db::rollback();
                return dyajaxReturn(0,$e->getMessage());
            }
        }else{
            return dyajaxReturn(0,"没有此模型");
        }
    }



    //添加为示例模型
    public function example(){
        $param = input("param.");
        $id = $param['id'];

        $ModuleModel = new ModuleModel();
        $mod = $ModuleModel -> where("id","=",$id)->find();
        $tablename = $mod['name'];

        $prefix = PREFIX;//表前缀
        $sql ="show full columns from ".$prefix . $tablename;
        $create_table_data = DB::query($sql);

        //获取表的所有字段
        $fields = '';
        foreach ($create_table_data as $k=>$v){
            $fields.= $v['Field'].',';
        }
        $fields = trim($fields,',');

        //所有字段数据
        $FieldsModel = new FieldsModel();
        $all_fields = $FieldsModel->where('moduleid',"=",$mod['id'])->select()->toArray();
        foreach ($all_fields as $k=>$v){
            unset($v['id']);
            unset($v['moduleid']);
            $all_fields[$k] = $v;
        }

        //所有索引数据
        //$sql ="SHOW INDEX FROM ".$prefix . $tablename;
        //$create_table_key_data = DB::query($sql);
        //return dyajaxReturn(0,"555",$create_table_key_data);

        $data['title'] = $mod['title'];
        $data['name'] = $mod['name'];
        $data['fields'] = $fields;
        $data['create_table_data'] = serialize($create_table_data);
        $data['create_fields_data'] = serialize($all_fields);
        $data['add_time'] = time();

        $ExampleModel = new ExampleModel();
        $ex_one = $ExampleModel -> where('name',"=",$mod['name'])->find();
        if(isset($ex_one['id']) && $ex_one['id']){
            return dyajaxReturn(0,"示例表已存在这个表名");
        }

        $ex_id = $ExampleModel -> insertGetId($data);
        if(!$ex_id){
            return dyajaxReturn(0,"添加失败");
        }
        return dyajaxReturn(1,"添加成功");
    }


   /*
    public function moduleState(){
       $id=input('post.id');
       $status=Db::name('module')->where(array('id'=>$id))->value('status');//判断当前状态情况

       if($status==1){
           $data['status'] = 0;
           Db::name('module')->where(array('id'=>$id))->update($data);
           $result['info'] = '状态禁止';
           $result['status'] = 1;

       }else{
           $data['status'] = 1;
           Db::name('module')->where(array('id'=>$id))->update($data);
           $result['info'] = '状态开启';
           $result['status'] = 1;
       }
       return $result;
   }
*/
   //删除模型
/*
    function del() {
        $id =input('param.id');
        $r = db('module')->find($id);
        if(!empty($r)){
            $tablename = config('database.prefix').$r['name'];
            $m = db('module')->delete($id);
            if($m){
                Db::execute("DROP TABLE IF EXISTS `".$tablename."`");
                db('Field')->where(array('moduleid'=>$id))->delete();
                $return = array(
                    'status' => 200,
                    'msg' => '删除成功！',
                );
                echo json_encode($return);
                exit();
            }
        }
    }
    */
    /*
   //字段管理 -- 改变字段状态
	public function fieldStatus(){
		$id = input('post.id');
		$fie = DB::name('field')->where('id',$id)->find();
		
		if($fie['status'] == 1){ 
			//启用变禁用
			$data['status'] = 0;
			$status = 'jing';
		}else{
			//禁用变启用
			$data['status'] = 1;
			$status = 'qi';
		}
		
		$res = DB::name('field')->where('id',$id)->update($data);
		
		$return = array(
			'status' => $status
		);
		echo json_encode($return);
	}
    */
    
    //字段管理
    public function fields(){
        //系统字段
        $param = input("param.");
        if(IS_AJAX){
            $FieldsModel = new FieldsModel();

            $res = $FieldsModel->tableData($param,"*",false);
            return dyajaxReturn($res['code'],$res['msg'],$res['data']);
        }else{
            $id = $param['id'];
            $ModuleModel = new ModuleModel();
            $modul_one = $ModuleModel -> where("id","=",$id)->find();

            View::assign('moduleid',$id);
            View::assign('modul_one',$modul_one);
            return View::fetch();
        }

        /*$list = DB::name('fields')->where("moduleid",'=',$id)
            ->order('orderid asc,id asc')->select();

        View::assign('list',$list);
        View::assign('moduleid',$id);

        View::assign('sysfield',array('catid','userid','username','title','thumb','keywords','description','posid','status','createtime','url','template'));
        View::assign('nodostatus',array('catid','title','status','createtime'));

        return View::fetch();*/
    }


    public function field_add_type(){
        $type = input('post.type');
        View::assign('type',$type);
        return view();
    }


    //字段添加
    public function field_add(){
        if(request()->isPost()){
            $data = input('post.');
            if($data['field'] == ''){
                return dyajaxReturn(0,'字段名不能为空');
            }
            if($data['name'] == ''){
                return dyajaxReturn(0,'别名不能为空');
            }
            if($data['field'] == 'file'){
                return dyajaxReturn(0,'file为系统保留字段，不可用');
            }
            if($data['field'] == 'siteid'){
                return dyajaxReturn(0,'siteid为系统保留字段，不可用');
            }
            if($data['field'] == 'catid'){
                return dyajaxReturn(0,'catid为系统保留字段，不可用');
            }
            //查找字段是否存在于数据表
            $model = new ModuleModel();
            $ishave = $model->field_exist($data);
            if($ishave) {
                return dyajaxReturn(0,'字段名已经存在！');
            }

            // 启动事务
            Db::startTrans();
            try {
                //获取操作表的sql语句
                $sql_res = $model->get_tablesql($data,'add');
                if(!$sql_res['code']){
                    Db::rollback();
                    return dyajaxReturn(0,$sql_res['msg']);
                }
                //return dyajaxReturn(0,'111',$sql_res);
                /*
                $field_str = 'varchar,textarea,select,editor,groupid,typeid,radio,checkbox,number,image,file';
                $field_arr = explode(',',$field_str);
                if(in_array($data['type'],$field_arr)){
                    if(empty($data['setup'])){ $this->error('请填写字段设置！');exit;}
                }
                */
                /*if(empty($data['class'])){
                    $data['class'] = $data['field'];
                }*/

                $data['fieldtype'] = $sql_res['data']['fieldtype'];
                $data['maxlength'] = $sql_res['data']['maxlength'];

                if(isset($data['setup']) && !empty($data['setup'])) {
                    //$data['setup'] = array3string($data['setup']);
                    $data['setup'] = json_encode($data['setup']);
                }
                //return dyajaxReturn(0,'字段新增失败',$data);
                $data['orderid']  = GetOrderID('fields');//排序
                $data['status'] = 1;
                $data['add_time'] = time();
                $res = DB::name('fields')->insertGetId($data);
                if(!$res){
                    Db::rollback();
                    return dyajaxReturn(0,'字段新增失败');
                }
                //字段插入表中的操作
                DB::execute($sql_res['data']['sql']);

                $module_one = DB::name("module")->where("id","=",$data['moduleid'])->find();
                adminLog($module_one['name']."表的".$data['field']."字段添加",$res);
                // 提交事务
                Db::commit();
                return dyajaxReturn(1,'字段新增成功','',(String)url('admin/module/fields',array('id'=>$data['moduleid'])) );
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return dyajaxReturn(0, $e->getMessage());
            }
        }else{
            $fieldType = config("app.fieldType");

            View::assign('fieldType',$fieldType);
            View::assign('moduleid',input('param.moduleid'));
            return View::fetch();
        }
    }

    public function field_edit_type(){
        $id = input('post.id');
        $type = input('post.type');

        $setup = DB::name('fields')->where('id',$id)->find();
        if($setup['setup']){
            //eval("\$arr = ".$setup['setup'].'; ');
            $arr = json_decode($setup['setup'],true);
        }
        if(!isset($arr['numbertype'])){$arr['numbertype'] = 0;}

        View::assign('setup',$arr);
        View::assign('type',$type);
        return View::fetch();
    }
    
    //字段修改
    public function field_edit(){
        if(request()->isPost()){
            $data = input('post.');
            if($data['field'] == ''){
                return dyajaxReturn(0,'字段名不能为空');
            }
            if($data['name'] == ''){
                return dyajaxReturn(0,'别名不能为空');
            }

            $id = $data['id'];
            $moduleid = $data['moduleid'];
            
            $new_field = DB::name('fields')->where('id','=',$id)->find();
            $data['oldfield'] = $new_field['field'];
            unset($data['id']);
            
            
            //查找字段是否存在于数据表
            $model = new ModuleModel();
            if($new_field['field'] != $data['field']){
                $ishave = $model->field_exist($data);
                if($ishave) { $this->error('字段名已经存在！');exit();}
            }

            // 启动事务
            Db::startTrans();
            try {
                //获取操作表的sql语句
                $sql_res = $model->get_tablesql($data,'edit');
                if(!$sql_res['code']){
                    Db::rollback();
                    return dyajaxReturn(0,$sql_res['msg']);
                }
                /*
                $field_str = 'varchar,textarea,select,editor,groupid,typeid,radio,checkbox,number,image,file';
                $field_arr = explode(',',$field_str);
                if(in_array($data['type'],$field_arr)){
                    if(empty($data['setup'])){ $this->error('请填写字段设置！');exit;}
                }
                */
                $data['fieldtype'] = $sql_res['data']['fieldtype'];
                $data['maxlength'] = $sql_res['data']['maxlength'];

                if(empty($data['class'])){
                    $data['class'] = $data['field'];
                }
                if(isset($data['setup']) && !empty($data['setup'])) {
                    //$data['setup'] = array3string($data['setup']);
                    $data['setup'] = json_encode($data['setup']);
                }
                unset($data['oldfield']);


                $res = DB::name('fields')->where('id',$id)->update($data);
                if(!$res){
                    Db::rollback();
                    return dyajaxReturn(0,'字段修改失败');
                }
                //字段插入表中的操作
                DB::execute($sql_res['data']['sql']);

                $module_one = DB::name("module")->where("id","=",$data['moduleid'])->find();
                adminLog($module_one['name']."表的".$data['field']."字段修改",$id);
                // 提交事务
                Db::commit();
                return dyajaxReturn(1,'字段修改成功','',(String)url('admin/module/fields',array('id'=>$data['moduleid'])) );
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return dyajaxReturn(0, $e->getMessage());
            }
        }else{
            $id = input('param.id');
            $row = DB::name('fields')->where('id',$id)->find();
            $fieldType = config("app.fieldType");
            View::assign('fieldType',$fieldType);
            View::assign('info',$row);
            View::assign('moduleid',input('param.moduleid'));
            return View::fetch();
        }
        
    }
    //字段删除
    function field_del() {
        $id=input('param.id');
        $prefix = config('database.connections.mysql.prefix');//表前缀

        $r=Db::name('fields')->find($id);
        $moduleid = $r['moduleid'];
        $name = DB::name('module')->where(array('id'=>$moduleid))->value('name');
        
        $field = $r['field'];//字段名
        $tablename=$prefix.$name;//表名

        DB::execute("ALTER TABLE `$tablename` DROP `$field`");
        
        $res = DB::name('fields')->delete($id);
        if(!$res){
            return dyajaxReturn(0,'字段删除失败');
        }
        adminLog($name."表的".$field."字段删除",$id);
        return dyajaxReturn(1,'字段删除成功');
    }

    //改变字段的排序
    public function changeFiledSort(){
        $param = input("param.");
        $id = $param['id'];
        $val = $param['val'];
        $FieldsModel = new FieldsModel();

        $res = $FieldsModel->where("id","=",$id)->update([
            'orderid'=>$val
        ]);
        if(!$res){
            return dyajaxReturn(0,'修改失败');
        }

        $field_one = $FieldsModel->where("id","=",$id)->find();
        $title = DB::name("module")->where("id","=",$field_one['moduleid'])->value("title");
        adminLog($title."模型的".$field_one['field']."字段改变排序为".$val,$id);
        return dyajaxReturn(1,'修改成功');
    }

    public function changeStatus(){
        $param = input('param.');
        $table = $param['table'];
        $id_name = $param['id_name'];
        $id = $param['id'];
        $field = $param['field'];
        $checked = $param['checked'];

        if($checked == 'true'){
            $res = DB::name($table) -> where($id_name,'=',$id)->update([$field=>1]);
        }else{
            $res = DB::name($table) -> where($id_name,'=',$id)->update([$field=>2]);
        }
        if(!$res){
            return dyajaxReturn(0,'操作失败');
        }
        return dyajaxReturn(1,'操作成功');
    }

    public function changeOrderid(){
        $param = input('param.');
        $table = $param['table'];
        $id_name = $param['id_name'];
        $id = $param['id'];
        $field = $param['field'];
        $val = $param['val'];

        $res = DB::name($table) -> where($id_name,'=',$id)->update([$field=>$val]);
        if(!$res){
            return dyajaxReturn(0,'操作失败');
        }
        adminLog($table.'表的排序修改为'.$val,$id);
        return dyajaxReturn(1,'操作成功');
    }

}
